package com.yzion.baselib.http

import android.text.TextUtils
import com.blankj.utilcode.util.*
import com.yzion.baselib.R
import com.yzion.baselib.utils.bodyToString
import com.yzion.baselib.utils.showToast
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

/**
 * 配合RequestHandlerInterceptor使用
 */
interface RequestHandler {
    /**
     * 请求前
     */
    fun onRequest(request: Request, chain: Interceptor.Chain): Request

    /**
     * 响应后
     */
    fun onResponse(response: Response, chain: Interceptor.Chain): Response
}

//请求头统一处理示例代码
/*
class HeaderHandler : RequestHandler {
    override fun onRequest(request: Request, chain: Interceptor.Chain): Request {
        var loginToken = ""
        if (LoginInfoBean.get()?.token != null) {
            loginToken = LoginInfoBean.get()!!.token!!
        }
        val curTime = System.currentTimeMillis().toString()
        return request.newBuilder()//处理请求头
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", loginToken)
            .addHeader("language", LanguageManager.get().currentLanguageCode)
            .addHeader("curTime", curTime)
            .addHeader("nonce", curTime)
            .addHeader("appId", BuildConfig.APP_ID)
            .addHeader("appKey", BuildConfig.APP_KEY)
            .addHeader("appSecret", BuildConfig.APP_SECRET)
            .addHeader("sign", createSign(request, BuildConfig.APP_SECRET, curTime, curTime))
            .build()
    }

    override fun onResponse(response: Response, chain: Interceptor.Chain): Response {
        //处理token失效问题
        var res: String? = null
        try {
            if (response.isSuccessful && response.body != null) {
                res = response.body!!.string()
                if (!TextUtils.isEmpty(res)) {
                    val apiResponse = GsonUtils.fromJson(res, ApiResponse::class.java)
                    if (apiResponse.code() == ResponseCode.UNAUTHORIZED_USER.code.toString()) {
                        ThreadUtils.runOnUiThread {
                            if (LoginManager.get().isLogin()) {
                                showToast(Utils.getApp().getString(R.string.token_fail))
                                //退出登陆重启应用
                                LoginManager.get().logout()
                                ThreadUtils.runOnUiThreadDelayed({
                                    AppUtils.relaunchApp()
                                }, 1000)
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        val body = res?.toResponseBody(response.body!!.contentType())
        return if (body == null) {
            response
        } else {
            //需要返回新的body，因为response.body!!.string()只能被调用一次，不然会报状态异常
            response.newBuilder().body(body).build()
        }
    }

    companion object {
        //创建签名
        private fun createSign(
            request: Request,
            appSecret: String,
            nonce: String,
            curTime: String
        ): String {
            val params = request.bodyToString()
            val s = appSecret + nonce + curTime + EncryptUtils.encryptMD5ToString(params)
            LogUtils.d("createSign:${s}")
            return EncryptUtils.encryptSHA1ToString(s).toLowerCase()
        }
    }

}
*/
